package cn.daniellee.plugin.el.listener;

import cn.daniellee.plugin.el.EnterLimiter;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class BungeeListener implements PluginMessageListener {

	@Override
	public void onPluginMessageReceived(String s, Player player, byte[] bytes) {
		ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
		String subChannel = in.readUTF();
		// 接收加时信息
		if (EnterLimiter.getInstance().isLimited() && "EnterLimiter".equals(subChannel)) {
			short length = in.readShort();
			byte[] msgBytes = new byte[length];
			in.readFully(msgBytes);
			DataInputStream msgIn = new DataInputStream(new ByteArrayInputStream(msgBytes));
			try {
				String name = msgIn.readUTF();
				int second = msgIn.readInt();
				Integer available = EnterLimiter.availableSecond.get(name);
				available = available == null ? second : available + second;
				EnterLimiter.availableSecond.put(name, available);
				EnterLimiter.getInstance().getPlayerData().set(name + ".available", available);
				EnterLimiter.getInstance().savePlayerData();
				// 更新总时长
				int total = EnterLimiter.getInstance().getPlayerData().getInt(name + ".total", 0);
				EnterLimiter.getInstance().getPlayerData().set(name + ".total", total + second);
				EnterLimiter.getInstance().savePlayerData();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
